package com.maxie.demo.lottery.event;


import com.maxie.demo.lottery.entity.LotteryResult;
import com.maxie.demo.lottery.event.listener.EventLinstener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 事件管理器
 * 订阅
 * 取消订阅
 * 发布
 */
public class EventManager {
    /**
     * 监听器列表
     */
    Map<Enum<EventType>, List<EventLinstener>> eventMap = new HashMap<>();

    public EventManager(Enum<EventType>... operations) {
        for (Enum<EventType> operation : operations) {
            eventMap.put(operation, new ArrayList<>());
        }
    }
    /**
     * 订阅:向 监听器列表 添加
     */
    public void subscribe(Enum<EventType> eventType, EventLinstener eventLinstener){
        List<EventLinstener> listenerVOS = eventMap.get(eventType);
        listenerVOS.add(eventLinstener);
    }

    public void unSubscribe(Enum<EventType> eventType, EventLinstener eventLinstener){
        List<EventLinstener> listenerVOS = eventMap.get(eventType);
        listenerVOS.remove(eventLinstener);
    }

    /**
     * notify
     */
    public void notify(Enum<EventType> eventType, LotteryResult result){
        List<EventLinstener> listenerVOS = eventMap.get(eventType);
        for (EventLinstener eventLinstener : listenerVOS) {
            eventLinstener.doEvent(result);
        }
    }


    /**
     * public 外部也需要使用
     */
    public enum EventType {
        EMAIL,
        MESSAGE
    }
}

